package org.geo.common.util;

import java.util.Random;

/**
 * 数字工具类
 *
 * @author ljy
 */
public class NumberUtil {
    private static Random RANDOM;

    static {
        RANDOM = new Random();
    }

    /**
     * 生成随机数
     *
     * @param maxNumber 最大为maxNumber
     * @return 随机整数
     */
    public static Integer randomInt(int maxNumber) throws IllegalArgumentException {
        if (maxNumber == 0) {
            return 0;
        }
        int result;
        if (maxNumber < 0) {
            result = -RANDOM.nextInt(-1 * maxNumber);
        } else {
            result = RANDOM.nextInt(maxNumber);
        }
        return result;
    }

    /**
     * 生成区间为[minNumber,maxNumber]的整数
     *
     * @param minNumber 最小数
     * @param maxNumber 最大数
     * @return 随机整数
     */
    public static Integer randomInt(int minNumber, int maxNumber) throws IllegalArgumentException {
        return RANDOM.nextInt(maxNumber - minNumber) + minNumber;
    }

    /**
     * 生成指定长度的随机数
     *
     * @param length 长度
     * @return 随机数
     * @throws IllegalArgumentException e
     */
    public static Integer generateRandomNumberByLength(int length) throws IllegalArgumentException {
        if (length <= 0) {
            throw new IllegalArgumentException("Length can not smaller than 0");
        }
        if (length == 1) {
            return RANDOM.nextInt(10);
        }
        int baseNum = (int) Math.pow(10.0, (length - 1) * 1.0);
        int tailNum = 0;
        for (int i = length - 1; i >= 1; i--) {
            tailNum = (int) (9 * Math.pow(10.0, (i - 1) * 1.0));
        }
        return RANDOM.nextInt((8 * baseNum + tailNum)) + baseNum;
    }

}
